﻿using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace FormProcessingTool
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : GWindow
    {
        private string encryptComputer = string.Empty;
        public MainWindow()
        {
            InitializeComponent();
            this.notifyIcon.DoubleClick += NotifyIcon_DoubleClick;
        }
        
        private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e) => e.Row.Header = e.Row.GetIndex() + 1;

        LogClass log = new LogClass();
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        string excelpath;
        string sheetName;
        int exportType = 0;//默认为去零合并版，1为自制清单，2为外购清单

        private void ImportTable_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Title = "打开excel文件";
            openFileDialog1.Filter = "Excel文件|*.xlsx;*.xls;*.csv";
            openFileDialog1.InitialDirectory = @"C:\Users\Administrator\Desktop";
            openFileDialog1.RestoreDirectory = true;
            if ((bool)openFileDialog1.ShowDialog())
            {
                excelpath = openFileDialog1.FileName;
                ArrayList al = ExcelSheetName(excelpath);
                if (al == null)
                {
                    return;
                }
                sheetName = (string)al[0];               

                ds = this.ExcelDataSource(excelpath, sheetName);
                dt = ds.Tables[0];

                dataGrid.ItemsSource = dt.Rows;
            }
            log.WriteLogFile("Import successfully");
        }

        public ArrayList ExcelSheetName(string filepath)
        {
            ArrayList al = new ArrayList();
            string strConn;
            string strFileType = System.IO.Path.GetExtension(filepath);
            strConn = " Provider=Microsoft.Ace.OleDb.12.0; " + " data source= " + filepath + " ;Extended Properties='Excel 12.0; HDR=Yes; IMEX=1' ";
            try
            {
                OleDbConnection conn = new OleDbConnection(strConn);
                conn.Open();
                DataTable sheetNames = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                conn.Close();
                foreach (DataRow dr in sheetNames.Rows)
                {
                    al.Add(dr[2]);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                log.WriteLogFile(ex.Message);
                return null;
            }     
          
            return al;
        }

        public DataSet ExcelDataSource(string filepath, string sheetname)
        {
            string strConn;
            string strFileType = System.IO.Path.GetExtension(filepath);
            DataSet ds = new DataSet();
            strConn = " Provider=Microsoft.Ace.OleDb.12.0; " + " data source= " + filepath + " ;Extended Properties='Excel 12.0; HDR=Yes; IMEX=1' ";
            try
            {
                OleDbConnection conn = new OleDbConnection(strConn);
                string strSql = string.Format(@"select * from [{0}]", sheetname);
                OleDbDataAdapter oada = new OleDbDataAdapter(strSql, strConn);
                oada.Fill(ds);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                log.WriteLogFile(ex.Message);
                return null;
            }
            
            return ds;
        }

        private void DeleteBlankLines_Click(object sender, RoutedEventArgs e)
        {
            foreach (DataRow item in dt.Rows)
            {
                if ((double)item.ItemArray[6] == 0)
                {
                    item.Delete();
                }
            }
            dt.AcceptChanges();
            dataGrid.ItemsSource = null;
            dataGrid.ItemsSource = dt.Rows;
        }

        private void MergerOfSimilarItems_Click(object sender, RoutedEventArgs e)
        {
            Hashtable hash = new Hashtable();
            ArrayList arrayList = new ArrayList();
            int count = 0;
            foreach (DataRow item in dt.Rows)
            {
                if (item[1].GetType().Name == "DBNull")
                {
                    count++;
                    continue;
                }
                if (!hash.ContainsKey((string)item.ItemArray[1]))
                {
                    hash.Add((string)item.ItemArray[1], count);
                }
                else
                {
                    DataRow datarow;
                    datarow = dt.Rows[(int)hash[(string)item.ItemArray[1]]];
                    datarow.BeginEdit();
                    datarow[6] = (double)datarow.ItemArray[6] + (double)item.ItemArray[6];
                    datarow.EndEdit();

                    arrayList.Add(item);
                }

                count++;
            }

            foreach (DataRow item in arrayList)
            {
                item.Delete();
            }

            dt.AcceptChanges();
            dataGrid.ItemsSource = null;
            dataGrid.ItemsSource = dt.Rows;
        }

        private void HomemadeList_Click(object sender, RoutedEventArgs e)
        {
            if (exportType == 2)
            {
                ds = this.ExcelDataSource(excelpath, sheetName);
                dt = ds.Tables[0];
            }
            exportType = 1;
            foreach (DataRow item in dt.Rows)
            {
                if ((string)item.ItemArray[7] == "外购")
                {
                    item.Delete();
                }
            }
            dt.AcceptChanges();
            dataGrid.ItemsSource = null;
            dataGrid.ItemsSource = dt.Rows;
        }

        private void OutsourcingList_Click(object sender, RoutedEventArgs e)
        {
            if (exportType == 1)
            {
                ds = this.ExcelDataSource(excelpath, sheetName);
                dt = ds.Tables[0];
            }
            exportType = 2;
            foreach (DataRow item in dt.Rows)
            {
                if ((string)item.ItemArray[7] == "自制")
                {
                    item.Delete();
                }
            }
            dt.AcceptChanges();
            dataGrid.ItemsSource = null;
            dataGrid.ItemsSource = dt.Rows;
        }

        private void ExportTable_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            dialog.Description = "请选择文件夹";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(dialog.SelectedPath))
                {
                    MessageBox.Show(this, "文件夹路径不能为空", "提示");
                    return;
                }
                else
                {
                    int index = excelpath.LastIndexOf("\\");
                    string savePath = dialog.SelectedPath+excelpath.Substring(index);
                    switch (exportType)
                    {
                        case 0:
                            savePath = savePath + "_new.csv";
                            break;
                        case 1:
                            savePath = savePath + "_自制清单.csv";
                            break;
                        case 2:
                            savePath = savePath + "_外购清单.csv";
                            break;
                        default:
                            break;
                    }
                    dataTableToCsv(savePath); //调用函数
                }
            }


            //int index = excelpath.LastIndexOf(".");
            //string savePath = excelpath.Substring(0, index);
            //switch (exportType)
            //{
            //    case 0:
            //        savePath = savePath + "_new.csv";
            //        break;
            //    case 1:
            //        savePath = savePath + "_自制清单.csv";
            //        break;
            //    case 2:
            //        savePath = savePath + "_外购清单.csv";
            //        break;
            //    default:
            //        break;
            //}
            //dataTableToCsv(savePath); //调用函数
        }


        private void dataTableToCsv(string fullPath)
        {
            FileInfo fi = new FileInfo(fullPath);
            if (!fi.Directory.Exists)
            {
                fi.Directory.Create();
            }
            FileStream fs = new FileStream(fullPath, FileMode.Create,FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
            string data = "";

            for (int i = 0; i < dt.Columns.Count; i++)//写入列名
            {
                data += dt.Columns[i].ColumnName.ToString();
                if (i < dt.Columns.Count - 1)
                {
                    data += ",";
                }
            }
            sw.WriteLine(data);

            for (int i = 0; i < dt.Rows.Count; i++) //写入各行数据
            {
                data = "";
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (j == 0)
                    {
                        string index = (i + 1).ToString();
                        data += index;
                    }
                    else
                    {
                        string str = dt.Rows[i][j].ToString();
                        str = str.Replace("\"", "\"\"");//替换英文冒号 英文冒号需要换成两个冒号
                        if (str.Contains(',') || str.Contains('"')
                            || str.Contains('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中
                        {
                            str = string.Format("\"{0}\"", str);
                        }
                        data += str;
                    }                    
                   
                    if (j < dt.Columns.Count - 1)
                    {
                        data += ",";
                    }
                }
                sw.WriteLine(data);
            }
            sw.Close();
            fs.Close();

            MessageBox.Show("导出成功！");
            log.WriteLogFile("Export successfully");
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string computer = ComputerInfo.GetComputerInfo();
            encryptComputer = new EncryptionHelper().EncryptString(computer);
            if (RegistFileHelper.ExistComputerInfofile())
            {
                string info = RegistFileHelper.ReadComputerInfoFile();
                if (encryptComputer != info)
                {
                    RegistFileHelper.WriteComputerInfoFile(encryptComputer);
                }
            }
            else
            {
                RegistFileHelper.WriteComputerInfoFile(encryptComputer);
            }

            if (CheckRegist() == true)
            {
                version.Visibility = Visibility.Visible;
                registerButton.Visibility = Visibility.Hidden;
            }
            else
            {
                version.Visibility = Visibility.Hidden;
                registerButton.Visibility = Visibility.Visible;
                exportTable.IsEnabled = false;               
            }
            log.WriteLogFile("Initialization successful");
        }

        private bool CheckRegist()
        {
            EncryptionHelper helper = new EncryptionHelper();
            string md5key = helper.GetMD5String(encryptComputer);
            return CheckRegistData(md5key);
        }

        private bool CheckRegistData(string key)
        {
            if (!RegistFileHelper.ExistRegistInfofile())
            {
                return false;
            }
            else
            {
                string info = RegistFileHelper.ReadRegistFile();
                var helper = new EncryptionHelper(EncryptionKeyEnum.KeyB);
                string registData = helper.DecryptString(info);
                if (key == registData)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        private void RegisterButton_Click(object sender, RoutedEventArgs e)
        {
            string fileName = string.Empty;
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "打开注册文件";
            openFileDialog.Filter = "KEY文件|*.key";
            if (openFileDialog.ShowDialog() == true)
            {
                fileName = openFileDialog.FileName;
            }
            else
            {
                return;
            }
            string localFileName = string.Concat(Environment.CurrentDirectory,System.IO.Path.DirectorySeparatorChar, RegistFileHelper.RegistInfofile);
            if (fileName != localFileName)
            {
                File.Copy(fileName, localFileName, true);
            }
            try
            {
                if (CheckRegist() == true)
                {
                    version.Visibility = Visibility.Visible;
                    registerButton.Visibility = Visibility.Hidden;
                    exportTable.IsEnabled = true;
                    MessageBox.Show("注册成功～");
                    log.WriteLogFile("Register successful");
                }
            }
            catch (Exception)
            {
                MessageBox.Show("请选择正确的注册文件！");
            }           
        }

        private void MenuItem_OpenClick(object sender, EventArgs e)
        {
            Open();
        }

        private void MenuItem_HelpClick(object sender, EventArgs e)
        {
            string filePath = Directory.GetCurrentDirectory() + "\\Readme.txt";
            if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
            {
                return;
            }

            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = filePath;
            psi.UseShellExecute = true;

            Process.Start(psi);
        }

        private void MenuItem_ExitClick(object sender, EventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void NotifyIcon_DoubleClick(object sender, EventArgs e)
        {
            Open();
        }

        private void Open()
        {
            this.Show();
            this.WindowState = WindowState.Normal;
            this.Activate();
        }
    }
}
